
#include "node.h"
#include "chessmind2.h"
#include "chesspane.h"
#include <stdlib.h>

// 棋局推演的局数。 >= 1。
const int MaxNodeLevel = 1;

Node::Node()
{
}

Node::Node(int x, int y, Node *parent)
{
    m = x;            //本节点位置
    n = y;
    //父节点为node，保存父节点指针
    pnode = parent;                 //保存起来给copy()使用
    nlevel = parent->nlevel + 1;    //本节点在树种的层数
    //当前节点是对上一层节点的对抗推演。取反色。
    if (pnode->myColor == BLACKCHESS) {
        myColor = WHITECHESS;
    } else {
        myColor = BLACKCHESS;
    }
    grid = pnode->grid;
    initial();
}

//父节点为node的初始化
void Node::initial()
{
    //_type='N';
    weight = 0;
    grid[m][n] = myColor;       //把本节点填到棋盘中

    /* 初始化完后，相当于已经把该节点填到棋盘，接下来计算权值 */
    calculateWeight();

    // 检测下一步的节点。
    if (nlevel < MaxNodeLevel)
        checkSubNode();
}

void Node::checkSubNode()
{
    //根据现有棋子，确定合法子节点空格
    Map valids = ChessMind2::BlackFilter(grid);

    for(Map::iterator it = valids.begin(); it != valids.end(); it ++){
        Node subnode(it->first, it->second, this);
        if (this->weight > subnode.weight)
            continue;
        //保存权值最大的子节点（多层节点树中，本身的权重会被覆盖！！！later）
        this->weight = subnode.weight;      
        this->bestm = subnode.m;
        this->bestn = subnode.n;
    }
}

#ifdef CHESS_DEBUG
#include <iostream>
using namespace std;
#endif

void Node::calculateWeight()
{
    // 倘若realgrid[m][n]点放我方的棋子，那么权重机会为：
    float attack = ChessMind2::AttackChance(grid, m, n);

    // 倘若放敌方棋子呢？？计算一下。。。看看有没有抢占的价值
    grid[m][n] = revertColor(grid[m][n]);
    //int defence = ChessMind2::DefendChance(grid, m, n);
    float defence = ChessMind2::AttackChance(grid, m, n);
    grid[m][n] = revertColor(grid[m][n]);

    weight = attack + defence;
#ifdef CHESS_DEBUG
    cout << "("<<m<<","<<n<<") \tA:"<<attack<<"\t D:"<<defence<<"\t W:"<<weight<<endl;
#endif
    //制造一个 - 0.0005 到 0.0005 之间的随机数，防止权重相同，(随机选出一个最大)
    weight = weight + ((double(rand()) / double(RAND_MAX)) - 0.5) * 0.001;
}


